import { BrowserHistory } from "history";
import React, { useEffect, useLayoutEffect, useMemo, useState } from "react"
import { baseName } from "../utils";
import history from "../utils/history"
import { debug } from "../utils/log";
// import { registerMicroApps} from 'qiankun';

export const MicroAppContext = React.createContext<MicroAppContextProps>({} as MicroAppContextProps);

interface RouteItemQiankun{
  container?:string
  activeRule?:any
  name?:any
}
interface RouteItemBase{
  path:string
  entry:string
  title?:string|((routeItem:RouteItemBase)=>string)
}
type RouteItem = RouteItemBase&RouteItemQiankun

interface MicroAppProviderProps {
  basename?: string
  children?: React.ReactNode,
  history?: BrowserHistory,
  defaultPage?: string
  modules?: any[],
  publicPath?: string
  spin?:React.ReactNode
  routes: any[]
  name: string
  notFound?: React.ReactNode
  env?: string
  ErrorBoundary?:React.ReactNode
}
interface MicroAppContextProps extends MicroAppProviderProps{
  routeMap:any

}
const createRouteMap = (routes)=>{
  let routeMap = {};

  const flatten = (_routes: any) => {
    _routes.forEach((item) => {
      if(Array.isArray(item.children)&&item.children.length>0){
     
        flatten(item.children);
      }else{
        routeMap[item.path] = {...item};
      }
      
    });
  };
  flatten(routes);

  return routeMap
}

export const MicroAppProvider = ({ modules = [],spin,ErrorBoundary, publicPath, name, defaultPage = '/', notFound, basename = '', routes, children }: MicroAppProviderProps) => {
  debug({publicPath})
  const [routeMap,setRouteMap] = useState({});
  const _history = React.useRef(history)
  useEffect(() => {
    _history.current = {
      ...history,
      push(a: any) {
        return history.push(baseName(basename as string, a))
      }
    }
    if (defaultPage!=location.pathname && ['/', basename + '/'].includes(location.pathname)) {
      history.push(baseName(basename as string, defaultPage));
    }

  }, [basename])
  useEffect(() => {

    (window as any).__micro_app = {
      name,
      routes
    };

  }, [])
  useEffect(() => {
    modules.forEach(module => {
      module.onRoutesChange && module.onRoutesChange(routes)
    })
     const _routeMap = createRouteMap(routes);
     setRouteMap({..._routeMap})
     debug({_routeMap})
  }, [routes])
  const value = useMemo(() => {
    
    return {
      routes,
      basename,
      name,
      publicPath,
      history: _history.current,
      defaultPage,
      modules,
      routeMap,
      spin,
      ErrorBoundary,
      notFound
    }
  }, [routeMap, _history.current])
  return <MicroAppContext.Provider value={value}>
    {children}
  </MicroAppContext.Provider>
}